package com.xiaoyg.algorithm;

import java.util.LinkedList;
import java.util.Queue;

public class MaxDepthTree {

    public static void main(String[] args) {
        TreeNode root  = new TreeNode(1);
        TreeNode root1  = new TreeNode(2);
        TreeNode root2  = new TreeNode(3);
        TreeNode root3  = new TreeNode(4);
        TreeNode root4  = new TreeNode(5);

        root.left = root1;
        root.right = root2;

        root1.left = root3;
        root1.right = root4;

        int maxDepth = maxDepthWithQueue(root);

        System.out.println(maxDepth);


    }

    public static int maxDepth(TreeNode root){
        if(root == null){
            return 0;
        }else{
            return Math.max(maxDepth(root.left),maxDepth(root.right)) + 1;
        }
    }

    public static int maxDepthWithQueue(TreeNode root){
        if (root == null) return 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int depth = 0;
        while (!queue.isEmpty()){
            int size = queue.size();
            while (size > 0){
                TreeNode poll = queue.poll();
                if (poll.left!=null){
                    queue.offer(poll.left);
                }
                if (poll.right!=null){
                    queue.offer(poll.right);
                }
                size--;
            }
            depth ++;
        }
        return depth;
    }

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }

        @Override
        public String toString() {
            return "TreeNode{" +
                    "val=" + val +
                    ", left=" + left +
                    ", right=" + right +
                    '}';
        }
    }
}
